package com.jie.base.init;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jie.base.mapper.CityMapper;
import com.jie.common.constant.LockKey;
import com.jie.common.constant.RedisKey;
import com.jie.common.util.LogUtil;
import com.jie.component.init.base.AbstractApplicationCommandLineRunnerHandler;
import com.jie.component.lock.util.ServiceLockTool;
import com.jie.component.threadpool.BusinessThreadPool;
import com.jie.model.po.base.City;
import com.jie.model.redis.base.CityRedis;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author jie
 * @version 1.0 2025-02-15
 */
@Component
@RequiredArgsConstructor
public class BaseDataCacheInit extends AbstractApplicationCommandLineRunnerHandler {

    private final StringRedisTemplate stringRedisTemplate;

    private final CityMapper cityMapper;

    private final ServiceLockTool serviceLockTool;

    @Override
    public Integer executeOrder() {
        return 0;
    }

    @Override
    public void executeInit(ConfigurableApplicationContext context) {
        BusinessThreadPool.execute(() -> serviceLockTool.execute(this::initCityCache, LockKey.BASE_DATA_INIT, new String[] {"city"}));
    }

    private void initCityCache() {
        LogUtil.initLog("城市数据缓存");
        LambdaQueryWrapper<City> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(City::getSortOrder);
        List<City> cities = cityMapper.selectList(queryWrapper);
        String key = RedisKey.getRedisKey(RedisKey.CITY);
        for (City city : cities) {
            CityRedis cityRedis = BeanUtil.copyProperties(city, CityRedis.class);
            stringRedisTemplate.opsForHash().put(key, city.getId().toString(), JSONUtil.toJsonStr(cityRedis));
        }
    }

}
